<template>
<div class="account-management">
    <!-- 左侧个人信息 -->
    <el-card   class="personal-info" shadow="never">
    <div class="clearfix">
        <span style = "font-weight: bold;">个人信息</span>
    </div>
    <div class="info-content" style="border-bottom: 1px solid #EBEEF5; padding: 20px 0;">
        <el-avatar :size="200" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
    </div>
    <table class="details-table">
        <tbody>
        <tr>
            <td class="left-column">账号:</td>
            <td class="right-column">{{ userInfo.id }}</td>
        </tr>
        <tr>
            <td class="left-column">用户名:</td>
            <td class="right-column">{{ userInfo.name }}</td>
        </tr>
        <tr>
            <td class="left-column">角色类型:</td>
            <td class="right-column"><el-tag type="info">{{ userInfo.role }}</el-tag></td>
        </tr>
        </tbody>
    </table>
    </el-card>

    <!-- 右侧基本信息和修改密码 -->
    <el-card v-loading="isLoading" class="basic-info" shadow="never">
    <div class="clearfix">
        <span style = "font-weight: bold;">基本资料</span>
    </div>
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="基本信息" name="basicInfo" >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="用户ID" prop="id">
                <el-input v-model="formData.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="name">
                <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="formData.phone"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save">保存</el-button>
            </el-form-item>
        </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="changePassword">
        <!-- 修改密码表单内容 -->
        <el-form ref="passwordFormRef" :model="passwordFormData" :rules="passwordRules" label-width="100px">
            <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="passwordFormData.oldPassword" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordFormData.newPassword" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmNewPassword">
                <el-input v-model="passwordFormData.confirmNewPassword" show-password></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="changePassword">修改</el-button>
            </el-form-item>
        </el-form>
        </el-tab-pane>
    </el-tabs>
    </el-card>
</div>
</template>

<script setup>

import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRoute } from 'vue-router';
import JSEncrypt from 'jsencrypt';

const route = useRoute();
const activeTab = ref('basicInfo');
const isLoading = ref(false);

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}` // 从 localStorage 获取 token 并设置到请求头
    }
})

onMounted(() => {
    fetchData();
});

const userInfo = reactive({
    id: '', 
    name: '',
    role: '',
});

const formData = reactive({
    id: '', 
    name: '',
    role: '',
    email: '',
    phone: ''
});

const rules = {
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' }
    ]
};

const formRef = ref(null);
const password = ref(null);
const role = ref(null);


// 清空密码表单的方法
const clearPasswordForm = () => {
    passwordFormData.oldPassword = '';
    passwordFormData.newPassword = '';
    passwordFormData.confirmNewPassword = '';
};
// 监听路由变化, 避免在其他页面修改影响本页面数据时不自动刷新的情况
watch(() => route.path, (newPath) => {
  if(newPath === '/common/AccountManagement') {
    console.error("刷新AccountManagement");
    fetchData();
  }
});
// 监听标签页切换事件
const handleTabClick = (tab) => {
    if (tab.paneName === 'basicInfo') {
        clearPasswordForm();
    }
}
const fetchData = () => {
    console.log("重新获取信息");
    isLoading.value = true;
    api.get('/api/v1/user/user-info', {
        params: {
            'userId': localStorage.getItem('id') // 使用 localStorage 中存储的 id 作为查询参数
        }}).then(response => {
        if (response.data.code == "200") {
            const data = response.data.data.records[0];
            console.log(JSON.stringify(data));
            userInfo.id = data.id;
            userInfo.name = data.name;
            userInfo.role = data.role;
            formData.id = data.id;
            formData.name = data.name;
            formData.email = data.email;
            formData.phone = data.phone;
            password.value = data.password;
            role.value = data.role;
            localStorage.setItem('role', data.role);
        } else {
            ElMessage.error('获取用户信息失败！' + response.data.message);
        }
    }).catch(error => {
        ElMessage.error('获取用户信息失败！' + error.message);
    }).finally(() => {
        isLoading.value = false;
    });
};

const save = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            isLoading.value = true;
            const params = {
                ...formData,
                password: null,
                role: role.value
            };
            console.error("password.value"+password.value);
            // // 如果 'id' 存在且有值，则替换为 'userId'
            // if ('code' in params && params.code) {
            //     params.userId = params.id;
            //     delete params.id;
            // }
            api.put('/api/v1/user/user-info', params).then(response => {
                if (response.data.code == "200"){
                    ElMessage({
                        title: '成功',
                        message: '保存成功',
                        type: 'success',
                        showClose: false,
                    });
                    isLoading.value = false;
                } else {
                    ElMessage({
                        title: '错误',
                        message: '保存失败！' + response.data.message,
                        type: 'error',
                    });
                }
            }).catch(error => {
                ElMessage({
                    title: '错误',
                    message: '保存失败！' + error.message,
                    type: 'error',
                });
            }).finally(() => {
                isLoading.value = false; // 结束加载，无论成功还是失败
                fetchData();
            });
        } else {
            ElMessage.error('请检查输入信息');
            isLoading.value = false; // 如果验证不通过，也需要结束加载状态
        }
    });
};

// 修改密码相关
const passwordFormRef = ref(null);
const passwordFormData = reactive({
    oldPassword: '',
    newPassword: '',
    confirmNewPassword: ''
});

const passwordRules = {
oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
    if (value !== password.value) {
        callback(new Error('密码错误'));
    } else {
        callback();
    }
    }, trigger: 'blur' }
],
newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
    { validator: (rule, value, callback) => {
    if(value === passwordFormData.oldPassword){
        callback(new Error('新密码和旧密码一致'));
    } else {
        callback();
    }
    }, trigger: 'blur' }
],
confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
    if (value !== passwordFormData.newPassword) {
        callback(new Error('两次输入的新密码不一致'));
    } else {
        callback();
    }
    }, trigger: 'blur' }
]
};
import { useStore } from 'vuex';
const store = useStore();
const changePassword = () => {
    passwordFormRef.value.validate((valid) => {
        if (valid) {
            isLoading.value = true;
            const encryptor = new JSEncrypt();
            console.error(JSON.stringify(store));
            encryptor.setPublicKey(store.getters.publicKey); // 从 Vuex 获取公钥
            const encryptedPassword = encryptor.encrypt(passwordFormData.confirmNewPassword); // 加密密码

            if (!encryptedPassword) {
                throw new Error('加密失败，请检查公钥是否正确');
            }
            api.put('/api/v1/user/user-info', { 
                id: localStorage.getItem('id'),
                password: encryptedPassword
             }).then(response => {
                console.error(JSON.stringify(response.data))
                if (response.data.code == "200"){
                    ElMessage({
                        title: '成功',
                        message: '修改密码成功',
                        type: 'success',
                        showClose: false,
                    });
                    passwordFormData.oldPassword="";
                    passwordFormData.newPassword="";
                    passwordFormData.confirmNewPassword="";
                    isLoading.value = false;
                } else {
                    ElMessage({
                        title: '错误',
                        message: '修改密码失败！' + response.data.message,
                        type: 'error',
                    });
                }
            }).catch(error => {
                ElMessage({
                    title: '错误',
                    message: '修改密码失败！' + error.message,
                    type: 'error',
                });
            }).finally(() => {
                isLoading.value = false;
                fetchData();
            });
        } else {
            ElMessage.error('请检查输入信息');
            isLoading.value = false;
        }
    });
};
</script>

<style scoped>
.account-management {
    display: flex;
    height: 100vh; /* 让整个容器占满视口高度 */
}
.personal-info {
  width: 30%; /* 左侧信息宽度设为40% */
  margin-right: 20px;
}

.basic-info {
  width: 70%; /* 右侧信息宽度设为60% */
}

.info-content {
    display: flex;
    justify-content: center; /* 居中对齐 */
    align-items: center;
    margin-top: 20px;
    padding: 20px 0; /* 添加内边距以增加空间 */
}

.clearfix {
    border-bottom: 1px solid #EBEEF5; /* 分割线 */
    padding-bottom: 10px;
}

.details-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 16px;
    font-family: Arial, sans-serif;
    margin-top: 10px;
}

.details-table tbody tr {
    border-bottom: 1px solid #EBEEF5; /* 分割线 */
}

.left-column, .right-column {
    padding: 25px 0; /* 给单元格添加内边距 */
}

.left-column {
text-align: left; /* 靠左对齐 */
padding-right: 10px;
width: 80px;
}

.right-column {
text-align: right; /* 靠右对齐 */
width: auto; /* 自动宽度 */
}
</style>